<template>
    <div class="oauth-callback-container">
        <el-card v-if="error" class="error-card">
            <template #header>
                <div class="error-header">
                    <el-icon>
                        <WarningFilled />
                    </el-icon>
                    <span>OAuth 登录失败</span>
                </div>
            </template>
            <p class="error-message">{{ errorMessage }}</p>
            <el-button type="primary" @click="backToLogin">返回登录页</el-button>
        </el-card>

        <el-card v-else class="success-card">
            <template #header>
                <div class="success-header">
                    <el-icon>
                        <CircleCheckFilled />
                    </el-icon>
                    <span>登录成功</span>
                </div>
            </template>
            <div class="loading-container">
                <el-avatar :size="64" :src="store.userAvatar" />
                <p class="welcome-text">欢迎回来，{{ store.userName }}</p>
                <p class="countdown-text">{{ countdown }}秒后自动跳转到首页...</p>
                <el-progress :percentage="progressPercentage" :format="() => ''" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores';
import { ElMessage } from 'element-plus';
import { WarningFilled, CircleCheckFilled } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const store = useAuthStore();

const error = ref(false);
const errorMessage = ref('');
const countdown = ref(5);
let timer = null;

const progressPercentage = computed(() => {
    return ((5 - countdown.value) / 5) * 100;
});

const backToLogin = () => {
    router.push('/login');
};

// 清理定时器
onBeforeUnmount(() => {
    if (timer) {
        clearInterval(timer);
    }
});

onMounted(async () => {
    try {
        const token = route.query.token;
        const error_msg = route.query.error;
        
        if (!token) {
            throw new Error('登录失败：缺少访问令牌');
        }
        if (error_msg) {
            throw new Error(decodeURIComponent(error_msg));
        }

        console.log('OAuth 回调收到 token:', token);
        
        // 先设置 token，确保后续请求带上认证头
        store.setToken(token);
        
        // 使用 authStore 的 loginWithToken 方法获取用户信息
        const success = await store.loginWithToken(token);
        
        if (!success) {
            throw new Error('登录失败：无法获取用户信息');
        }

        // 确保登录状态已经设置
        if (!store.isAuthenticated) {
            throw new Error('登录失败：认证状态异常');
        }

        console.log('OAuth 登录成功，token 已设置，用户信息已获取');

        // 倒计时跳转
        timer = setInterval(() => {
            countdown.value--;
            if (countdown.value <= 0) {
                clearInterval(timer);
                console.log('倒计时结束，准备跳转到首页');
                router.push('/');  // 使用路由跳转，让路由守卫正常工作
            }
        }, 1000);
    } catch (e) {
        error.value = true;
        errorMessage.value = e.message;
        console.error('OAuth 处理错误:', e);
        ElMessage.error(e.message);
    }
});
</script>

<style scoped>
.oauth-callback-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f5f7fa;
    padding: 20px;
}

.error-card,
.success-card {
    width: 400px;
    text-align: center;
}

.error-header,
.success-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 20px;
}

.welcome-text {
    font-size: 18px;
    color: #303133;
    margin: 10px 0;
}

.countdown-text {
    color: #909399;
    margin: 5px 0;
}

.error-message {
    color: #f56c6c;
    margin: 20px 0;
}

:deep(.el-progress-bar__inner) {
    transition: all 1s linear;
}
</style>